package com.sxj.PDMS.controller.admin;

import cn.hutool.core.io.FileUtil;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.DeleteRequest;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.constant.UserConstant;
import com.sxj.PDMS.context.BaseContext;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.model.dto.student.StudentUpdateRequest;
import com.sxj.PDMS.model.entity.Student;
import com.sxj.PDMS.model.dto.student.StudentSelectRequest;
import com.sxj.PDMS.service.StudentManageService;
import com.sxj.PDMS.service.StudentService;
import com.sxj.PDMS.utils.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Slf4j
public class StudentManageController {
    @Autowired
    private StudentManageService studentManageService;

    @Autowired
    private StudentService studentService;

    /**
     * 批量注册学生账号
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/register_student")
    public BaseResponse registerStudents(@RequestPart("file") MultipartFile multipartFile,
                                         HttpServletRequest request) {

        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 10M");
        // 校验文件后缀 aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");

        // 读取学生信息
        List<Student> studentList = ExcelUtils.excelToStudentList(multipartFile);

        // 批量注册学生账号
        studentManageService.registerStudentBatch(studentList);

        // 返回成功信息
        return Result.success();
    }

    /**
     * 更新学生信息
     *
     * @param studentUpdateRequest
     * @return
     */
    @PutMapping("/update_student")
    public BaseResponse<Boolean> updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {

        // todo 校验参数格式
        if (studentUpdateRequest == null || studentUpdateRequest.getStudentNumber() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Student student = new Student();
        BeanUtils.copyProperties(studentUpdateRequest, student);

        // todo 修改成根据传过来的参数修改 没传的不修改
        boolean result = studentService.updateById(student);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return Result.success(true);
    }


    /**
     * 删除学生
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean b = studentService.removeById(deleteRequest.getId());
        return Result.success(b);
    }


    /**
     * 分页查询学生信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    //todo:/用户信息脱敏
    @GetMapping("/selectAll_student")
    public BaseResponse<PagingQueryResponse> selectAllStudent(@RequestParam(defaultValue = "1") Integer page,
                                                              @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<Student> pagingQueryResponse = studentManageService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    /**
     * 根据条件分页查询学生信息
     *
     * @param page
     * @param pageSize
     * @param studentSelectRequest
     * @return
     */
    //todo:/用户信息脱敏
    @GetMapping("/select_student")
    public BaseResponse<PagingQueryResponse<Student>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                          @RequestParam(defaultValue = "10") Integer pageSize,
                                                                          StudentSelectRequest studentSelectRequest) {
        log.info("根据条件分页查询 ：page:{}, pageSize:{},studentSelectRequest:{}", page, pageSize, studentSelectRequest);

        PagingQueryResponse<Student> pagingQueryResponse = studentManageService.selectWithCondition(page, pageSize, studentSelectRequest);

        return Result.success(pagingQueryResponse);
    }

    /**
     * 根据条件查询并下载学生信息
     *
     * @param studentSelectRequest
     * @return
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAllStudentAndDownload", produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_student")
//    @ApiOperation(value = "", produces = "application/octet-stream")
    public void selectAllStudentAndDownload(StudentSelectRequest studentSelectRequest,
                                            HttpServletResponse response) {
        log.info("根据条件查询并下载学生信息 ：studentSelectRequest:{}", studentSelectRequest);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "学生基本信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            studentManageService.selectAllStudentAndDownload(studentSelectRequest, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载学生信息失败");
        }
    }

    /**
     * 获取学生信息
     *
     * @param studentNumber
     * @return
     */
    @GetMapping("/get_info/{studentNumber}")
    public BaseResponse<Student> getStudentInfo(@PathVariable String studentNumber) {
        log.info("获取学生信息,{}", studentNumber);
        Student student = studentService.getById(studentNumber);
        if (student == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        student.setPassword(null);

        return Result.success(student);
    }

    /**
     * 用户更新信息
     *
     * @param studentUpdateRequest
     * @param request
     * @return
     */
    @PutMapping("/modify_info")
    public BaseResponse<Boolean> updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest,
                                               HttpServletRequest request) {
        log.info("管理员{}更新学生信息,{}", BaseContext.getCurrentId(), studentUpdateRequest);

        if (studentUpdateRequest == null || studentUpdateRequest.getStudentNumber() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Student student = new Student();
        BeanUtils.copyProperties(studentUpdateRequest, student);
        boolean result = studentService.updateById(student);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }
}
